var _CertData = function () {
  let loadCertType = (cb)=>{
    if (_CertData.certTypes){
      return cb&&cb(_CertData.certTypes);
    }
    $$.list("cert_type",(list)=>{
      _CertData.certTypes = {};
      $.each(list,(k,v)=>{
        _CertData.certTypes[v["id"]] = v;
      });
      cb && cb(_CertData.certTypes);
    })
  };
  let loadFont = (cb) => {
    if (_CertData["fonts"]) {
      return cb && cb();
    }
    $$.list("font", (list) => {
      let m = {};
      $.each(list, (k, v) => {
        // let sc = document.createElement("script");
        // sc.src = v["path"] + "?" + v["id"];
        // $("sc").attr("id", v["id"]);
        let src = v["path"] + "?" + v["id"];
        $("head").append(`<script src="${src}"></script>`);
      });
      _CertData["fonts"] = m;
      loadCertType(()=>{cb&&cb()});
    })
  };
  let loadCertList = (data, cb) => {
    loadFont(() => {
      let result = [];
      $$.list("cert", data, (list) => {
        list.forEach(item => {
          let ids = JSON.parse(item["certTypeIds"]) || [];
          if (ids.length == 1) {
            item["certTypeId"] = ids[0];
            item["certTypeName"] = _CertData.certTypes[item["certTypeId"]];
            result.push(item);
            return;
          }
          $.each(ids, (k, v) => {
            let newItem = $.extend({}, item);
            newItem["certTypeId"] = v;

            result.push(newItem);
          });
        });
        result = result.sortBy(["certTypeId", "defaultCert desc"]);

        cb && cb(result);
      },"type,name,defaultCert DESC");
    })
    
  };
  let loadCert = (id, cb) => {
    let cert = _CertData["certs"][id];
    if (!cert) {
      $$.fetch("cert", id, (cert) => {
        (cert.items || []).forEach(item => {
          if (/^\[(.*?)\]$/.test(item.text)) {
            try {
              item.texts = JSON.parse(item.text);
            } catch (e) {
            }
          } else {
            item.texts = item.text;
          }
        });
        if (cert.pic) {
          
          $.get(cert.pic, (r) => {
            cert.picData = r;
            cb && cb(cert);
          });
          // 不能用，生成的图片太大
          // loadBase64(cert.pic,(data)=>{
          //   cert.picData = data;
          //   cb && cb(cert);
          // });
        }else{
          cb && cb(cert);
        }

        _CertData["certs"][id] = cert;
        
      }, (r) => cb && cb(null, r))
    } else {
      cb && cb(cert);
    }
  };
  let loadBase64 = (picUrl, cb) => {
    var img = new Image();
    img.onerror = function(e){
      alert("err");
    };
    img.onload = function() {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      
      var dataURL = canvas.toDataURL("image/png");
      canvas.remove();
      cb && cb(dataURL);
    };
    // img.src = escape(picUrl);
    img.src = picUrl;
  };
  return {
    "fonts": null,
    "certs": {},
    "certTypes" :null,
    loadFont,
    loadBase64,
    loadCertList,
    loadCert,
    loadCertType,
    
  };
}();
